<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="添加商品信息" center show-icon type="info"> </el-alert>

      <!-- 步骤条 -->
      <el-steps :space="200" align-center :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 侧边栏选项卡 -->
      <el-form label-position="top" :model="goodInfo" :rules="goodInforules" ref="ruleForm" label-width="100px">
        <el-tabs @tab-click="tabclickFn" v-model="activeIndex" tab-position="left" :before-leave="leaveFn">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodInfo.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodInfo.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodInfo.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodInfo.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="goodInfo.goods_cat" :options="goodsList" :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children' }" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="text" v-for="(text, i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in OnlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals" placeholder=""></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :on-success="imgUploadSuccess" :headers="headerObj" class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="goodInfo.goods_introduce"></quill-editor>
            <el-button type="primary" class="addBtn" @click="addInfo">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片弹框 -->
    <el-dialog title="预览图片" :visible.sync="imgdialogVisible" width="50%">
      <img :src="previewImgUrl" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import { getCategoriesList, getcategoryListbyId , addGoods} from '@/api/index.js'

export default {
  created() {
    getCategoriesList({})
      .then((res) => {
        this.goodsList = res.data.data
      })
      .catch((err) => {
        this.$message.error('获取商品分类失败')
      })
  },
  data() {
    return {
      //*预览图片地址
      previewImgUrl: '',
      //*预览图片弹框
      imgdialogVisible: false,
      //*设置上传图片请求头
      headerObj: {
        Authorization: sessionStorage.getItem('token'),
      },
      //*上传的图片列表
      fileList: [],
      //*商品分类列表
      goodsList: [],
      //*激活的选项卡
      activeIndex: '0',
      //*表单信息
      goodInfo: {
        goods_name: '',
        goods_cat: [],
        goods_price: 1,
        goods_number: 1,
        goods_weight: 0,
        pics: [],
        goods_introduce: '',
        attrs: [],
      },
      //*表单规则
      goodInforules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
      },
      //*动态参数列表
      manyTabData: [],
      //*静态参数列表
      OnlyTabData: [],
    }
  },
  methods: {
    //*添加商品提交数据
    addInfo() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.$message.success('填写正确')
          let formInfo = JSON.parse(JSON.stringify(this.goodInfo))
          formInfo.goods_cat = this.goodInfo.goods_cat.join(',')
          
          this.manyTabData.forEach((item,index) => {
            formInfo.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') })
          })
          this.OnlyTabData.forEach((item) => {
            formInfo.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals})
          })
          let {data:res} = await addGoods(formInfo)
          if(res.meta.status != 201) {return this.$message.error('添加商品失败')}
          this.$message.success('添加商品成功')
          this.$router.push('/home/goods')
        } else {
          this.$message.error('请填写必填项')
        }
      })
    },
    //*图片上传成功回调
    imgUploadSuccess(res, file, fileList) {
      this.goodInfo.pics.push({ pic: res.data.tmp_path })
    },
    //*删除回调
    handleRemove(file) {
      
      let index = ''
      this.goodInfo.pics.forEach((item, i) => {
        if ((item.pic = file.response.data.tmp_path)) {
          index = i
        }
      })
      this.goodInfo.pics.splice(index, 1)
    },
    //*预览回调
    handlePreview(file) {
      this.previewImgUrl = file.response.data.url
      this.imgdialogVisible = true
    },
    //*选项卡单击事件
    async tabclickFn() {
      if (this.activeIndex == '1') {
        let { data: res } = await getcategoryListbyId(this.goodInfo.goods_cat[2] - 0, 'many')
        if (res.meta.status != 200) {
          return this.$message.error('获取数据失败')
        }
        // console.log(res)
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
      } else if (this.activeIndex == '2') {
        let { data: res } = await getcategoryListbyId(this.goodInfo.goods_cat[2] - 0, 'only')
        //console.log(res)
        if (res.meta.status != 200) {
          return this.$message.error('获取数据失败')
        }
        this.OnlyTabData = res.data
      }
    },
    //*Prevent tab switching events
    leaveFn() {
      if (this.activeIndex == 0 && this.goodInfo.goods_cat.length != 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    //* 选中不是三级标签，就清空选中项
    handleChange() {
      if (this.goodInfo.goods_cat.length != 3) {
        this.goodInfo.goods_cat = []
      }
    },
  },
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 8px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>
